import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {
  PageContainer,
  ProDescriptions,
  ProTable,
  ProField
} from '@ant-design/pro-components';
import '@umijs/max';
import {Descriptions, Drawer, message, Popconfirm, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {SortOrder} from "antd/es/table/interface";
import {
  bindOrLifeUsingPost,
  getUserVoByIdUsingPost,
  pageUsersUsingPost as pageUsingPost
} from "@/services/easyapi/eUserCenter";
import EmpowerOrRevoke from "@/pages/TableList/components/EmpowerOrRevoke";
import user from "../../../mock/user";

export enum UserOperationActions {
  BIND_USER = "bindUser",
  LIFT_USER = "liftUser",
  EMPOWER_USER = "empowerUser",
  REVOKE_USER = "revokeUser",
}

const TableList: React.FC = () => {
  const [empowerVisible, handleEmpowerVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.ApiCenterUserVo>();
  const [userDetail, setUserDetail] = useState<API.ApiCenterUserVo>();
  const bindOrLifeUser = async (user: API.ApiCenterUserVo) => {
    const action = user.userStatues === 0 ? UserOperationActions.BIND_USER : UserOperationActions.LIFT_USER
    await bindOrLifeUsingPost({
      userId: user.id,
      action: action
      //@ts-ignore
    }).then(res => {
      actionRef.current?.reload();
    })
  }

  const getUserVoByUserId = async (id: number) => {
    const res = await getUserVoByIdUsingPost({
      //@ts-ignore
      userId: id,
    });
    if (res.code === 200) {
      setUserDetail(res.data)
    } else {
      setUserDetail(res.data);
      message.error(res.msg);
    }
  }

  // @ts-ignore
  const columns: ProColumns<API.ApiCenterUserVo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInForm: true
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      valueType: 'textarea',
    },
    {
      title: '用户头像',
      dataIndex: 'userAvatar',
      sorter: false,
      search: false,
      valueType: 'image',
    },
    {
      title: '用户账户',
      dataIndex: 'userAccount',
      hideInForm: true,
    },
    {
      title: '邮箱',
      dataIndex: 'userEmail',
      hideInForm: true
    },
    {
      title: '用户状态',
      dataIndex: 'userStatues',
      valueEnum: {
        0: {
          text: '正常',
          status: 'Processing',
        },
        1: {
          text: '关闭',
          status: 'Default',
        },
      },
    },
    {
      title: '性别',
      dataIndex: 'gender',
      render(text) {
        return (
          (text === 0 ? '男' : '女')
        )
      },
      valueEnum: {
        1: {
          text: '男',
        },
        0: {
          text: '女',
        },
      },
    },
    {
      title: '创建时间',
      hideInForm: true,
      search: false,
      dataIndex: 'createAt',
      valueType: 'dateTime',
    },
    {
      title: '更新时间',
      search: false,
      hideInForm: true,
      dataIndex: 'updateAt',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        record.id === 1 ? <></> :
          <a
            key="config"
            onClick={() => {
              handleEmpowerVisible(true)
              setCurrentRow(record)
            }}
          >
            授权
          </a>,
        record.id === 1 ? <></> :
          record.id === 1 ? <></> :
            <Popconfirm
              title={`确定要${record.userStatues === 0 ? '禁用' : '恢复'}该用户吗?`}
              onConfirm={() => bindOrLifeUser(record)}  // 确认后执行操作
              okText="是"
              cancelText="否"
            >
              <a
                key="config1"
                style={{color: record.userStatues === 0 ? 'red' : 'green'}}
              >
                {record.userStatues === 0 ? "禁用" : "恢复"}
              </a>
            </Popconfirm>,
        <a onClick={() => {
          setCurrentRow(record)
          setShowDetail(true)
          //@ts-ignore
          getUserVoByUserId(record.id)
        }}>详情</a>
      ],
    },
  ];

  // @ts-ignore
  return (
    <PageContainer>
      <ProTable<API.ApiCenterUserVo, API.UserPageParam>
        headerTitle={'用户列表'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}

        request={async (params
          , sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const res = await pageUsingPost({
            ...params
          } as API.UserPageParam);
          if (res.code === 200) {
            return {
              // @ts-ignore
              data: res?.data.records,
              success: true,
              // @ts-ignore
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />
      <EmpowerOrRevoke visible={empowerVisible} onCancel={() => {
        handleEmpowerVisible(false)
      }} onSubmit={() => {
        alert("提交")
      }}
        //@ts-ignore
                       user={currentRow}/>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        <ProDescriptions
          column={2}
          title={userDetail?.userAccount}
          dataSource={userDetail}  // This sets the data
        >
          <ProDescriptions.Item label="用户账户">
            <Tag color="green" style={{fontSize: '15px'}}>
             {userDetail?.userAccount}
            </Tag>
          </ProDescriptions.Item>
          <ProDescriptions.Item label="">
            <ProField
              text="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
              valueType="image"
              mode="read"
            />
          </ProDescriptions.Item>
          <ProDescriptions.Item label="用户名">
            <Tag color="green" style={{fontSize: '15px'}}>
            {userDetail?.userName}
            </Tag>
          </ProDescriptions.Item>
          <ProDescriptions.Item label="用户邮箱">
            <Tag color="green" style={{fontSize: '15px'}}>
              用户账户: {userDetail?.userEmail}
            </Tag>
          </ProDescriptions.Item>
          <ProDescriptions.Item label="性别">
            <ProField
              text={userDetail?.gender}
              valueEnum={{
                0:{
                  text:'男',
                  status:'Success'
                },
                1:{
                  text:'女',
                  status:'W',
                  color:'pink'
                },
              }}
              mode="read"
            />
          </ProDescriptions.Item>
          <ProDescriptions.Item label="账户状态">
            <ProField
              text={userDetail?.userStatues}
              valueEnum={{
                0:{
                  text:'正常',
                  status:'Success'
                },
                1:{
                  text:'禁用',
                  status:'Error'
                },
                2:{
                  text:'异常',
                  status:'Exception'
                }
              }}
              mode="read"
            />
          </ProDescriptions.Item>
          <ProDescriptions.Item label="创建时间">
            <ProField
              text={userDetail?.createAt}
              valueType="dateTime"
              mode="read"
              plain={false}
            />
          </ProDescriptions.Item>
          <ProDescriptions.Item label="更新时间">
            <ProField
              text={userDetail?.updateAt}
              valueType="dateTime"
              mode="read"
              plain={false}
            />
          </ProDescriptions.Item>
          <ProDescriptions.Item label="角色列表" span={2} >
            <ProField
              text={userDetail?.role?.map((role, index) => (
                <Tag color="blue" key={index} style={{ marginBottom: '5px' }}>
                  {role}
                </Tag>
              ))}
              mode="read"
              plain={false}
            />
          </ProDescriptions.Item>
          <ProDescriptions.Item label="权限列表" span={2} >
            <ProField
              text={userDetail?.permissions?.map((role, index) => (
                <Tag color="purple" key={index} style={{ marginBottom: '5px' }}>
                  {role}
                </Tag>
              ))}
              mode="read"
              plain={false}
            />
          </ProDescriptions.Item>
        </ProDescriptions>

      </Drawer>
    </PageContainer>
  );
};
export default TableList;
